<template>
	<view class="order-detail-page">
		<!-- 订单状态 -->
		<view class="status-banner" :class="getStatusClass(orderDetail.status)">
			<view class="status-main">{{ getStatusText(orderDetail.status) }}</view>
			<view class="status-sub">订单{{ getStatusText(orderDetail.status) }}</view>
		</view>

		<!-- 物流信息 -->
		<view class="logistics-section">
			<view class="logistics-content">
				<text class="logistics-text">暂无物流信息</text>
			</view>
		</view>

		<!-- 收货人信息 -->
		<view class="recipient-section">
			<view class="recipient-info">
				<text class="recipient-name">{{ orderDetail.consigneeName  }}</text>
				<text class="recipient-phone">{{ orderDetail.consigneePhone  }}</text>
				<text class="recipient-address">地址:{{ orderDetail.consigneeAddress  }}</text>
			</view>
		</view>

		<!-- 店铺和商品信息 -->
		<view class="store-section">
			<view class="store-name">{{ orderDetail.storeName  }}</view>
			<view class="product-list">
				<view v-for="(product, index) in orderDetail.products" :key="index" class="product-item">
					<image :src="product.image" class="product-image" mode="aspectFill" />
					<view class="product-info">
						<view class="product-name">{{ product.name }}</view>
						<view class="product-price-info">
							<text class="product-price">¥{{ product.price  }}</text>
							<text class="refund-info">全部退款(¥0.00)</text>
						</view>
					</view>
					<view class="product-right">
						<text class="product-status" :class="getStatusClass(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</text>
						<text class="product-quantity">x{{ product.quantity }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 价格明细 -->
		<view class="price-section">
			<view class="price-item">
				<text class="price-label">商品总价:</text>
				<text class="price-value">¥{{ orderDetail.totalAmount }}</text>
			</view>
			<view class="price-item">
				<text class="price-label">优惠券:</text>
				<text class="price-value discount">{{orderDetail.products && orderDetail.products.length > 0 ? orderDetail.products[0].couponAmount : 0}}</text>
			</view>
			<view class="price-item" >
				<text class="price-label">活动优惠:</text>
				<text class="price-value discount">-¥{{ getActivityDiscount().toFixed(2) }}</text>
			</view>
			<view class="price-item total">
				<text class="price-label">总计:</text>
				<text class="price-value">¥{{ orderDetail.totalAmount  }}</text>
			</view>
		</view>

		<!-- 服务 -->
		<view class="service-section">
			<view class="service-title">服务</view>
			<button class="service-btn" @click="contactService">联系客服</button>
		</view>

		<!-- 订单详情 -->
		<view class="order-info-section">
			<view class="order-info-item">
				<text class="info-label">订单编号:</text>
				<view class="info-content">
					<text class="info-value">{{ orderDetail.id  }}</text>
					<button class="copy-btn" @click="copyOrderId">复制</button>
				</view>
			</view>
			<view class="order-info-item">
				<text class="info-label">下单时间:</text>
				<text class="info-value">{{ orderDetail.createTime }}</text>
			</view>
			<view class="order-info-item">
				<text class="info-label">订单备注:</text>
				<text class="info-value">暂无备注</text>
			</view>
			<view class="order-info-item">
				<text class="info-label">支付状态:</text>
				<text class="info-value">{{ getPaymentStatusText(orderDetail.status) }}</text>
			</view>
			<view class="order-info-item">
				<text class="info-label">支付方式:</text>
				<text class="info-value">暂无</text>
			</view>
		</view>

		<!-- 底部应付金额 -->
		<view class="bottom-amount">
			<text class="amount-label">应付金额:</text>
			<text class="amount-value">¥{{ orderDetail.totalAmount }}</text>
		</view>
	</view>
</template>

<script>
import { post } from '@/config/request.js';

export default {
	name: 'OrderDetail',
	data() {
		return {
			orderId: '',
					orderDetail: {
			id: '',
			storeName: '',
			status: '',
			totalAmount: 0,
			createTime: '',
			consigneeName: '',
			consigneePhone: '',
			consigneeAddress: '',
			products: []
		}
		}
	},
	onLoad(options) {
		console.log('订单详情页面参数:', options);
		
		// 获取传递的订单ID
		if (options.orderId && options.orderId !== 'undefined') {
			this.orderId = options.orderId;
		}
		
		// 获取传递的订单数据
		if (options.orderData) {
			try {
				const parsedData = JSON.parse(decodeURIComponent(options.orderData));
				// 验证数据完整性 - 支持多种数据结构
				const hasValidId = parsedData && parsedData.id && parsedData.id !== 'undefined';
				const hasValidProducts = parsedData && (
					(parsedData.products && Array.isArray(parsedData.products) && parsedData.products.length > 0) ||
					(parsedData.orderProductList && Array.isArray(parsedData.orderProductList) && parsedData.orderProductList.length > 0)
				);
				
				if (hasValidId && hasValidProducts) {
					// 如果数据结构不完整，需要格式化
					if (!parsedData.products && parsedData.orderProductList) {
						// 将 orderProductList 转换为 products 格式
						this.orderDetail = this.formatOrderDetail(parsedData);
					} else {
						this.orderDetail = parsedData;
					}
					console.log('解析后的订单数据:', this.orderDetail);
				} else {
					console.warn('订单数据不完整，将重新获取');
					// 尝试使用部分有效数据
					if (hasValidId) {
						this.orderDetail = {
							...this.getDefaultOrderDetail(),
							...parsedData,
							products: this.formatProducts(parsedData.orderProductList || [])
						};
						console.log('使用部分有效数据:', this.orderDetail);
					} else {
						this.orderDetail = this.getDefaultOrderDetail();
					}
				}
			} catch (error) {
				console.error('解析订单数据失败:', error);
				this.orderDetail = this.getDefaultOrderDetail();
			}
		}
		
		// 如果没有传递数据或数据不完整，尝试根据订单ID获取详情
		if (!this.orderDetail.id || !this.orderDetail.products || this.orderDetail.products.length === 0) {
			if (this.orderId) {
				this.loadOrderDetail();
			} else {
				// 如果没有订单ID，显示错误提示
				uni.showToast({
					title: '缺少订单信息',
					icon: 'none'
				});
			}
		}
	},
	methods: {
		// 获取默认订单详情
		getDefaultOrderDetail() {
			return {
				id: '',
				storeName: '',
				status: '',
				totalAmount: 0,
				createTime: '',
				consigneeName: '',
				consigneePhone: '',
				consigneeAddress: '',
				products: []
			};
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 获取订单详情
		async loadOrderDetail() {
			// 验证订单ID是否有效
			if (!this.orderId || this.orderId === 'undefined') {
				uni.showToast({
					title: '订单ID无效',
					icon: 'none'
				});
				return;
			}
			
			try {
				uni.showLoading({
					title: '加载中...'
				});
				const res = await post('/orders/order/detail', {
					orderId: this.orderId
				});
				
				uni.hideLoading();
				
				if (res.statusCode === 200 && res.data.code === 200) {
					this.orderDetail = this.formatOrderDetail(res.data.result);
				} else {
					uni.showToast({
						title: '获取订单详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('获取订单详情失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},
		
		// 格式化订单详情数据
		formatOrderDetail(apiData) {
			return {
				id: apiData.id || apiData.orderId,
				storeName: apiData.storeName || '杂货铺',
				status: this.mapApiStatusToLocal(apiData.orderStatus),
				totalAmount: apiData.orderAmount || apiData.totalAmount || 0,
				createTime: apiData.createTime,
				consigneeName: apiData.consigneeName || apiData.buyerName || apiData.receiverName || '收货人',
				consigneePhone: apiData.consigneePhone || apiData.receiverPhone || apiData.phone,
				consigneeAddress: apiData.consigneeAddress || apiData.receiverAddress || apiData.address,
				products: this.formatProducts(apiData.orderProductList || [])
			};
		},
		
		// 格式化商品数据
		formatProducts(orderItems) {
			return orderItems.map(item => ({
				name: item.goodsName || item.productName || item.name || '商品',
				price: item.price || item.unitPrice || item.productPrice || 0,
				quantity: item.num || item.quantity || item.productQuantity || 1,
				image: item.goodsImage || item.productImage || item.image || '/static/img/a.png',
				couponAmount: item.couponAmount || item.discount || 0
			}));
		},
		
		// 将API状态映射到本地状态
		mapApiStatusToLocal(apiStatus) {
			console.log('映射订单状态:', apiStatus);
			
			const statusMap = {
				// 英文状态
				'UNPAID': 'unpaid',
				'UNDELIVERED': 'unshipped',
				'DELIVERED': 'unreceived',
				'COMPLETE': 'completed',
				'CANCELLED': 'canceled',
				// 中文状态
				'已关闭': 'canceled',
				'待付款': 'unpaid',
				'已付款': 'paid',           // 修正：已付款状态
				'待发货': 'unshipped',
				'已发货': 'shipped',        // 新增：已发货状态
				'待收货': 'unreceived',
				'已收货': 'received',
				'已完成': 'completed',
				'已取消': 'canceled'
			};
			
			const mappedStatus = statusMap[apiStatus] || 'unpaid';
			console.log('映射后状态:', mappedStatus);
			
			return mappedStatus;
		},
		
		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'unpaid': '待付款',
				'paid': '已付款',           // 新增：已付款
				'unshipped': '待发货',
				'shipped': '已发货',        // 新增：已发货
				'unreceived': '待收货',
				'received': '已收货',       
				'completed': '已完成',
				'canceled': '已取消'
			};
			return statusMap[status] || '未知状态';
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			const classMap = {
				'unpaid': 'status-unpaid',
				'paid': 'status-paid',           // 新增：已付款样式
				'unshipped': 'status-unshipped',
				'shipped': 'status-shipped',     // 新增：已发货样式
				'unreceived': 'status-unreceived',
				'received': 'status-received',   
				'completed': 'status-completed',
				'canceled': 'status-canceled'
			};
			return classMap[status] || '';
		},
		
		// 获取支付状态文本
		getPaymentStatusText(status) {
			if (status === 'unpaid' || status === 'canceled') {
				return '未付款';
			} else if (status === 'paid' || status === 'unshipped' || status === 'shipped' || status === 'unreceived' || status === 'received' || status === 'completed') {
				return '已付款';
			} else {
				return '未知';
			}
		},
		
		// 复制订单号
		copyOrderId() {
			uni.setClipboardData({
				data: this.orderDetail.id,
				success: () => {
					uni.showToast({
						title: '订单号已复制',
						icon: 'success'
					});
				}
			});
		},
		
		// 联系客服
		contactService() {
			uni.navigateTo({
				url: '/pages/kefu/kefu'
			});
		},
		
		// 计算总优惠券金额
		getTotalCouponAmount() {
			if (!this.orderDetail.products || this.orderDetail.products.length === 0) {
				return 0;
			}
			
			return this.orderDetail.products.reduce((sum, product) => {
				return sum + (product.couponAmount || 0);
			}, 0);
		},
		
		// 计算活动优惠金额
		getActivityDiscount() {
			if (!this.orderDetail.products || this.orderDetail.products.length === 0) {
				return 0;
			}
			
			// 计算商品原价总和
			const originalTotal = this.orderDetail.products.reduce((sum, product) => {
				return sum + (product.price * product.quantity);
			}, 0);
			
			// 活动优惠 = 商品原价总和 - 订单总金额
			const discount = originalTotal - this.orderDetail.totalAmount;
			
			// 只返回正数，避免显示负数
			return Math.max(0, discount);
		}
	}
}
</script>

<style lang="scss" scoped>
.order-detail-page {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.nav-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
	position: sticky;
	top: 0;
	z-index: 100;
}

.nav-left, .nav-right {
	display: flex;
	align-items: center;
}

.nav-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.nav-icon {
	font-size: 36rpx;
	color: #666;
	margin: 0 10rpx;
}

.nav-left, .nav-right {
	display: flex;
	align-items: center;
}

.nav-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.nav-icon {
	font-size: 36rpx;
	color: #666;
	margin: 0 10rpx;
}

.status-banner {
	padding: 40rpx 30rpx;
	text-align: center;
	
	&.status-canceled {
		background-color: #ff6b35;
	}
	
	&.status-unpaid {
		background-color: #ff9500;
	}
	
	&.status-paid {
		background-color: #34c759;
	}
	
	&.status-unshipped {
		background-color: #007aff;
	}
	
	&.status-shipped {
		background-color: #007aff;
	}
	
	&.status-unreceived {
		background-color: #34c759;
	}
	
	&.status-received {
		background-color: #34c759;
	}
	
	&.status-completed {
		background-color: #34c759;
	}
}

.status-main {
	font-size: 48rpx;
	color: #fff;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.status-sub {
	font-size: 28rpx;
	color: #fff;
	opacity: 0.9;
	padding: 10rpx;
}

.logistics-section, .recipient-section, .store-section, .price-section, .service-section, .order-info-section {
	background-color: #fff;
	margin: 20rpx 20rpx 0 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
	
	&:last-child {
		margin-bottom: 20rpx;
	}
}

.logistics-content {
	text-align: center;
}

.logistics-text {
	font-size: 28rpx;
	color: #999;
}

.recipient-info {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.recipient-phone {
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
}

.recipient-address {
	font-size: 28rpx;
	color: #666;
	line-height: 1.4;
}

.store-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.product-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	
	&:last-child {
		border-bottom: none;
	}
}

.product-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	line-height: 1.4;
}

.product-price-info {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.product-price {
	font-size: 30rpx;
	color: #ff4444;
	font-weight: bold;
}

.refund-info {
	font-size: 24rpx;
	color: #ff6b35;
}

.product-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 10rpx;
}

.product-status {
	font-size: 24rpx;
	
	&.status-canceled {
		color: #ff6b35;
	}
	
	&.status-unpaid {
		color: #ff9500;
	}
	
	&.status-paid {
		color: #34c759;
	}
	
	&.status-unshipped {
		color: #007aff;
	}
	
	&.status-shipped {
		color: #007aff;
	}
	
	&.status-unreceived {
		color: #34c759;
	}
	
	&.status-received {
		color: #34c759;
	}
	
	&.status-completed {
		color: #34c759;
	}
}

.product-quantity {
	font-size: 26rpx;
	color: #fa0505;
}

.price-item {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	padding: 15rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	gap: 20rpx;
	
	&:last-child {
		border-bottom: none;
	}
	
	.price-label {
		font-size: 28rpx;
		color: #666;
		min-width: 140rpx;
	}
	
	.price-value {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		
		&.discount {
			color: #ff6b35;
		}
	}
	
	&.total {
		border-top: 2rpx solid #e0e0e0;
		margin-top: 10rpx;
		padding-top: 20rpx;
		
		.price-label {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
		}
		
		.price-value {
			font-size: 32rpx;
			font-weight: bold;
			color: #ff4444;
		}
	}
}

.price-label {
	font-size: 28rpx;
	color: #666;
}

.price-value {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
	margin-left: 10rpx;
	
	&.discount {
		color: #ff6b35;
	}
}

.service-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.service-btn {
	background-color: #f5f5f5;
	color: #666;
	border: none;
	padding: 20rpx 40rpx;
	border-radius: 25rpx;
	font-size: 28rpx;
}

.order-info-item {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	gap: 20rpx;
	
	&:last-child {
		border-bottom: none;
	}
	
	.info-label {
		font-size: 28rpx;
		color: #666;
		min-width: 140rpx;
	}
	
	.info-content {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}
	
	.info-value {
		font-size: 28rpx;
		color: #333;
		max-width: 400rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.copy-btn {
		background-color: #f5f5f5;
		color: #666;
		border: none;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
	}
}



.bottom-amount {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 30rpx;
	border-top: 1rpx solid #eee;
	display: flex;
	justify-content: flex-start;
	align-items: center;
	gap: 20rpx;
}

.amount-label {
	font-size: 32rpx;
	color: #333;
}

.amount-value {
	font-size: 36rpx;
	color: #ff4444;
	font-weight: bold;
}
</style>
